<template>
  <view id="amap" class="map">
    <view class="map-controls" v-if="selectedScooter">
      <view class="scooter-info">
        <text class="scooter-id">Scooter #{{ selectedScooter.id }}</text>
        <text class="price">${{ selectedScooter.price }}/hour</text>
        <button class="rent-btn" @click="rentScooter(selectedScooter)">Rent Now</button>
      </view>
    </view>
  </view>
  <cover-image :markers="markers" :change:markers="aMapRenderJs.getmarkers"></cover-image>
</template>

<script>
import { showScooter } from '@/service/scooter'
export default {
  data() {
    return {
      // 当前位置
      currentLocation: {
        latitude: 23.12,
        longitude: 113.48,
      },
      // 标记点
      markers: [],
      selectedScooter: null,
    }
  },
  methods: {
    // 获取当前位置

    getCurrentLocation() {
      const locationMarker = {
        id: 'current',
        name: 'Current Location',
        latitude: 23.12,
        longitude: 113.48,
        iconPath: './static/icons/location.png', // 确保有这个图标
        width: 32,
        height: 32,
        customCallout: {
          anchorY: 0,
          anchorX: 0,
          display: 'ALWAYS',
        },
      }
      uni.getLocation({
        type: 'gcj02',
        geocode: true,
        success: (res) => {
          this.currentLocation.latitude = res.latitude
          this.currentLocation.longitude = res.longitude
        },
        fail: (err) => {
          console.error(err)
          uni.showToast({
            title: '获取位置失败',
            icon: 'none',
          })
        },
      })
      this.markers = [...this.markers, locationMarker]
    },

    // 获取 scooter 数据
    async getScooterData() {
      try {
        const res = await showScooter()

        if (res.data) {
          const scooterMarkers = res.data.map((item, index) => ({
            id: item.id,
            name: item.scooterName,
            latitude: item.latitude,
            longitude: item.longitude,
            iconPath: './static/icons/scooter.png',
            width: 45,
            height: 45,
            number: item.orderCount || 0,
            customCallout: {
              anchorY: 0,
              anchorX: 0,
              display: 'ALWAYS',
            },
          }))
          this.markers = [...this.markers, ...scooterMarkers]
        }
      } catch (error) {
        uni.showToast({
          title: 'Get scooter data failed',
          icon: 'none',
        })
      }
    },

    // 租用 scooter
    rentScooter(scooter) {
      console.log(scooter)
      if (scooter.id === 'current') {
        return
      }
      uni.navigateTo({
        url: `/pages/rent/index?scooterId=${scooter.id}&longitude=${scooter.longitude}&latitude=${scooter.latitude}`,
      })
    },
  },
  mounted() {
    // 获取 scooter 数据
    this.getCurrentLocation()
    console.log(this.markers)
    this.getScooterData()
  },
}
</script>

<script module="aMapRenderJs" lang="renderjs">
const A_MAP_KEY = "cd60afb4e5a22c569f4c42ce75a34be5"; // 地图key
const A_MAP_SECRET_KEY = "8c30043dbe2ac5dbcedaa5f2e7320d48"; // 地图密钥

export default {
	data() {
		return {
			map: null,
			markersList: []
		}
	},
	mounted() {
		this.getmarkers()
		// 地图初始化
		if (typeof window.AMap === 'function') {
			this.initAmap();
		} else {
			window._AMapSecurityConfig = {
				securityJsCode: A_MAP_SECRET_KEY,
			};
			const script = document.createElement('script');
			script.src = `https://webapi.amap.com/maps?v=1.4.15&key=${A_MAP_KEY}&plugin=AMap.Walking`;
			script.onload = this.initAmap.bind(this);
			document.head.appendChild(script);
		}
	},
	methods: {
		getmarkers(e) {
			if (e) {
				this.markersList = e
			}
		},
		// 初始化
		initAmap() {
			const that = this
			this.map = new AMap.Map('amap', {
				resizeEnable: true,
				zoom: 14,
				center: [113.48, 23.12], // 初始化地图中心点位置
			})
			setTimeout(function() {
				that.markersList.forEach(item => {
					const wicon = new AMap.Icon({
						size: new AMap.Size(45, 45), // 图标尺寸
						image:item.iconPath, // Icon的图像
						imageSize: new AMap.Size(45, 45) // 根据所设置的大小拉伸或压缩图片
					});
					const wmarker = new AMap.Marker({
						position: [item.longitude, item.latitude],
						offset: new AMap.Pixel(-10, -10),
						icon: wicon, // 添加 Icon 实例

					});
					that.map.add(wmarker);
					const wcontent = `${item.name}` ;
					const wmarkert = new AMap.Marker({
						content: wcontent, // 自定义点标记覆盖物内容
						position: [item.longitude, item.latitude],
						offset: new AMap.Pixel(-55, -55) // 相对于基点的偏移位置
					});
					that.map.add(wmarkert);
					// 添加点击事件
					wmarker.on('click', function(e) {
						console.log(that.$ownerInstance.callMethod,"事情",e)
						that.$ownerInstance.callMethod('rentScooter', item)
					})

				})
			}, 200)

		},
		// 修改 updateMarkers 方法
		updateMarkers() {
			if (!this.map || !this.markersList.length) return;

			this.map.clearMap();

			// 更新地图中心点为当前位置
			const currentMarker = this.markersList.find(item => item.id === 'current');
			if (currentMarker) {
				this.map.setCenter([currentMarker.longitude, currentMarker.latitude]);
			}

			this.markersList.forEach(item => {
				const isCurrentLocation = item.id === 'current';

				const icon = new AMap.Icon({
					size: new AMap.Size(isCurrentLocation ? 32 : 45, isCurrentLocation ? 32 : 45),
					image: isCurrentLocation ?  './static/icons/scooter.png':'./static/icons/location.png',
					imageSize: new AMap.Size(isCurrentLocation ? 32 : 45, isCurrentLocation ? 32 : 45)
				});

				const marker = new AMap.Marker({
					position: [item.longitude, item.latitude],
					offset: new AMap.Pixel(-10, -10),
					icon,
				});
				this.map.add(marker);

				if (!isCurrentLocation && item.number !== undefined) {
					const content = `<div class="bgs">当前接单量：${item.number}单</div>`;
					const labelMarker = new AMap.Marker({
						content,
						position: [item.longitude, item.latitude],
						offset: new AMap.Pixel(-55, -55)
					});
					this.map.add(labelMarker);
				}
			});
		}
	}
}
</script>

<style lang="scss">
.bgs {
  background-color: #fff;
  border-radius: 10px;
  padding: 10px 15px;
  font-size: 14px;
}

.map {
  width: 100%;
  height: 100vh;
  position: relative;

  .number-bg {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 20rpx 30rpx;
    font-size: 28rpx;
  }
}

.map-controls {
  position: absolute;
  bottom: 20px;
  left: 20px;
  right: 20px;

  .scooter-info {
    background: #fff;
    border-radius: 12px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: space-between;

    .scooter-id {
      font-size: 16px;
      font-weight: bold;
    }

    .price {
      color: #f60;
      font-weight: bold;
    }

    .rent-btn {
      background: #007aff;
      color: #fff;
      padding: 6px 12px;
      border-radius: 6px;
      border: none;
    }
  }
}

.marker-label {
  white-space: nowrap;
  text-align: center;
}
</style>
